﻿using MediatR;
using ModelContextProtocol.Server;
using ProduceBasicData.Api.Application.Command.Weather;
using ProduceBasicData.Domain.Weather;
using System.ComponentModel;
using System.Text;

namespace ProduceBasicData.Api.Untis
{
    /// <summary>
    /// 天气预警MCP工具（供大模型调用，生成生产活动预警）
    /// </summary>
    [McpServerToolType]
    public class WeatherAlertTool
    {
        private readonly IMediator _mediator;

        public WeatherAlertTool(IMediator mediator)
        {
            _mediator = mediator;
        }

        /// <summary>
        /// 获取指定城市的天气并生成生产预警
        /// 【action: get-weather-alerts-for-production】
        /// </summary>
        [McpServerTool(Name = "get-weather-alerts")]
        [Description("获取指定城市的天气信息并生成生产活动预警，返回可能影响生产的天气预警列表")]
        public async Task<string> GetWeatherAlertsAsync(
            [Description("城市编码，如上海=310000")] string cityCode,
            [Description("生产计划ID（可选）")] long? productionPlanId = null,
            [Description("相关生产流程（可选）")] string? relevantProcess = null)
        {
            var command = new GenerateWeatherAlertCommand
            {
                CityCode = cityCode,
                //ProductionPlanId = productionPlanId,
                //RelevantProcess = relevantProcess
            };

            var result = await _mediator.Send(command);
            return FormatAlertsForModel(result.Data);
        }

        /// <summary>
        /// 为指定经纬度位置获取天气预警
        /// 【action: get-weather-alerts-by-coordinates】
        /// </summary>
        [McpServerTool(Name = "get-weather-alerts-by-coords")]
        [Description("根据经纬度获取天气信息并生成生产活动预警")]
        public async Task<string> GetWeatherAlertsByCoordinatesAsync(
            [Description("纬度，如39.9042")] double latitude,
            [Description("经度，如116.4074")] double longitude,
            [Description("生产计划ID（可选）")] long? productionPlanId = null)
        {
            var command = new GenerateWeatherAlertCommand
            {
                Latitude = latitude,
                Longitude = longitude,
                //ProductionPlanId = productionPlanId
            };

            var result = await _mediator.Send(command);
            return FormatAlertsForModel(result.Data);
        }

        /// <summary>
        /// 将预警信息格式化为大模型易理解的字符串
        /// </summary>
        private string FormatAlertsForModel(List<WeatherAlert>? alerts)
        {
            if (alerts == null || !alerts.Any())
            {
                return "当前及未来几天天气状况良好，对生产活动无显著影响。";
            }

            var sb = new StringBuilder();
            sb.AppendLine("检测到以下可能影响生产的天气预警：");

            foreach (var alert in alerts)
            {
                sb.AppendLine($"- 预警类型：{alert.WeatherType}（{GetAlertLevelName(alert.AlertLevel)}）");
                sb.AppendLine($"  影响范围：{alert.AffectRange}");
                sb.AppendLine($"  建议措施：{alert.Suggestion}");
                sb.AppendLine($"  生成时间：{alert.GenerateTime:yyyy-MM-dd HH:mm}");
                sb.AppendLine();
            }

            return sb.ToString();
        }

        /// <summary>
        /// 将预警等级枚举转换为中文名称
        /// </summary>
        private string GetAlertLevelName(AlertLevel level)
        {
            return level switch
            {
                AlertLevel.Blue => "蓝色预警",
                AlertLevel.Yellow => "黄色预警",
                AlertLevel.Orange => "橙色预警",
                AlertLevel.Red => "红色预警",
                _ => "未知等级"
            };
        }
    }
}
